//
//  StatusListViewModel.swift
//  weiboLQ
//
//  Created by 半缘君 on 15/12/11.
//  Copyright © 2015年 banyuanjun.cn. All rights reserved.
//

import Foundation
import SDWebImage
class StatusListViewModel {
    
   lazy var statusList = [StatusViewModel]()
    
    func loadData (isPullup isPullup:Bool,finished:(isSuccess:Bool) -> ()) {
    
    // 下拉刷新 id
    let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
    // 上拉刷新 id
    let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0
    
        StatusDAL.shareStatusDAL.loadStatus(since_id, max_id: max_id) { (array) -> () in
            
            guard let array = array else {
                finished(isSuccess: false)
                return
            }
            var statusL = [StatusViewModel]()
            //遍历数组,字典转模型
            for dic in array {
                statusL.append(StatusViewModel(status: StatusModel(dic: dic)))
//                print(dic)
            }
            if max_id > 0{
                self.statusList += statusL
            } else {
            self.statusList = statusL + self.statusList
            }
            
            finished(isSuccess: true)
            
        }
    }
    
    private func cacheSingleImage(dataList: [StatusViewModel], finished: (isSuccessed: Bool)->()) {
        
        // 1. 创建调度组
        let group = dispatch_group_create()
        // 缓存数据长度
        var dataLength = 0
        
        // 2. 遍历视图模型数组
        for vm in dataList {
            
            // 判断图片数量是否是单张图片
            if vm.thumbnail_pics?.count != 1 {
                continue
            }
            
            // 获取 url
            let url = vm.thumbnail_pics![0]
            print("开始缓存图像 \(url)")
            
            // SDWebImage - 下载图像(缓存是自动完成的)
            // 入组 - 监听后续的 block
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(
                url,
                options: [],
                progress: nil,
                completed: { (image, _, _, _, _) -> Void in
                    
                    // 单张图片下载完成 － 计算长度
                    if let img = image,
                          data = UIImagePNGRepresentation(img) {
                            // 累加二进制数据的长度
                            dataLength += data.length
                    }
                    
                    // 出组
                    dispatch_group_leave(group)
            })
        }
        
        // 3. 监听调度组完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("缓存完成 \(dataLength / 1024) K")
            
            // 完成回调 - 控制器才开始刷新表格
            finished(isSuccessed: true)
        }

}
}